package li.rafa.UrlShortener.server;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import li.rafa.UrlShortener.client.UrlService;
import li.rafa.UrlShortener.shared.ShortUrl;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class UrlServiceImpl extends RemoteServiceServlet implements UrlService {

	@Override
	public ShortUrl getShortenedUrl(String originalUrl, String optionalKeyWord) {
		PersistenceManager pm = PMF.getPM();
		try {
			if (optionalKeyWord != null && optionalKeyWord.trim().length()>0) {
				Query query = pm.newQuery(ShortUrl.class);
				query.setFilter("code == codeParam");
				query.declareParameters("String codeParam");
				List<ShortUrl> persistedShortUrls = (List<ShortUrl>) query.execute(optionalKeyWord);
				if (persistedShortUrls.size() > 0) {
					return persistedShortUrls.get(0);
				} else if (originalUrl!=null) {
					ShortUrl shortUrl = new ShortUrl(originalUrl);
					shortUrl.setCode(optionalKeyWord);
					return pm.makePersistent(shortUrl);
				} else {
					return new ShortUrl(originalUrl);
				}
			} else {
				Query query = pm.newQuery(ShortUrl.class);
				query.setFilter("originalUrl == originalUrlParam");
				query.declareParameters("String originalUrlParam");
				List<ShortUrl> persistedShortUrls = (List<ShortUrl>) query.execute(originalUrl);
				if (persistedShortUrls.size()>0) {
					return persistedShortUrls.get(0);
				} else {
					ShortUrl shortUrl = new ShortUrl(originalUrl);
					pm.makePersistent(shortUrl);
					shortUrl.setCode(ToolUrl.base48Encode(shortUrl.getId()));
					return shortUrl;
				}
			}
		} finally {
			pm.close();
		}
	}

}
